/**
 * 验证码
 */

import { Random } from 'mockjs';
import moment from 'moment';
import db from '../../utils/dbconf';
import { sendCodeMail } from '../../utils/mail';

export const TABLE_NAME = 'TOOL_CODE';

export default {
	// 注册验证码
	sendReginCode: async (mail) => {
		const code = Random.string(8);
		const endtime = new Date(new Date().getTime() + 1000 * 60 * 20).toLocaleString();
		await sendCodeMail({ to: mail, time: endtime, code });
		const id = await db.table(TABLE_NAME).add({ mail, endtime, code: code.toLowerCase() });
		return id;
	},
	// 验证
	checkCode: async (mail, code) => {
		code = code.toLowerCase();
		const { id, endtime } = await db.table(TABLE_NAME).where({ mail, code, used: 0 }).find();
		if (!endtime) throw new Error('验证码错误');
		if (moment(endtime).isBefore(new Date())) throw new Error('验证码已过期');
		return id;
	},
	// 用完之后废弃
	checkOver: async (id) => {
		await db.table(TABLE_NAME).where({ id }).update({ used: 1 });
	},
};
